package cn.mabach.oauth2.authentication;

import cn.mabach.oauth2.properties.props.LoginType;
import cn.mabach.oauth2.properties.SecurityProperties;
import cn.mabach.oauth2.utils.CookieUtils;
import cn.mabach.oauth2.utils.RS;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证成功处处理器理器
 * 1. 决定 响应json还是跳转页面，或者认证成功后进行其他处理
 */
@Component
@Slf4j
public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private ClientDetailsService clientDetailsService;


    @Autowired
    private AuthorizationServerTokenServices defaultAuthorizationServerTokenServices ;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//根据clientId获取ClientDetails
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(securityProperties.getOauth2().getClientId());


//        封装TokenRequest 所需参数 第一个参数是封装了不同授权模式所需要的参数，第二个参数是client_id，第三个参数是scope,第四个参数是grant_types
        TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP, securityProperties.getOauth2().getClientId(),
                clientDetails.getScope(),"custom");

//        第一步 用TokenRequest 和ClientDetails 创建OAuth2Request
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
//      第二部 用参数传进来的authentication和自定义的OAuth2Request 封装成OAuth2Authentication



        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);

//创建令牌

        OAuth2AccessToken accessToken = defaultAuthorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        log.info("令牌是：{}",accessToken);

        String name = authentication.getName();


        logger.info("登录成功");
        log.info("记录用户登录日志 用户名：{}",name);
//如果是app请求则返回JSON
        if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(RS.ok(accessToken.getValue())));

        }


//        返回如果是浏览器请求则把令牌存进cookies，然后重定向
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(RS.ok(accessToken)));
        CookieUtils.setCookie(request,response,"Authorization",accessToken.getValue(),24*60*60*30*12);
//        CookieUtil.addCookie(response,"http://www.mabach.cn","/","Authorization",accessToken.getValue(),-1,false);




//        String url=null;
//        // 获取上一次请求路径
//        String referer = request.getHeader("Referer");
//
//        int i = referer.indexOf("from=");
//        if (i==-1){
//
//        }
//        url= referer.substring(i + 5);
//        log.info("上一次请求是:{}",url);
//
//        super.setDefaultTargetUrl(url);
//        super.onAuthenticationSuccess(request, response, authentication);



    }
}
